<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { mobileRules, passwordRules, codeRules } from '@/utils/rules'
import { showToast } from 'vant'
import type { FormInstance } from 'vant'
import { loginByPassword, sendMobileCode, loginByMobile } from '@/services/user'
import { useUserStore } from '@/stores'
import { useRouter, useRoute } from 'vue-router'

const store = useUserStore()
const router = useRouter()
const route = useRoute()

const agree = ref<boolean>(false)
const mobile = ref()
const password = ref()
const code = ref()

const isPass = ref(true) // 短信登录密码登录切换 true密码登录
const isShow = ref(true) // 是否显示密码
// 表单提交
const login = async () => {
  if (!agree.value) return showToast('请勾选我同意')

  const res = isPass.value
    ? await loginByPassword(mobile.value, password.value)
    : await loginByMobile(mobile.value, code.value)
  // console.log('res.data', res.data)
  // 获取到的用户信息存储到仓库中, 并且保存到本地
  store.setUser(res.data)

  // 如果有回调地址进行回调, 没有回调地址进入个人中心
  router.push((route.query.returnUrl as string) || '/user')
  showToast('登录成功!')
}

const formRef = ref<FormInstance>()
const timer = ref(0) // 发送验证码之后的定时器
let timeId: number
// 发送验证码
const sentCode = async () => {
  // 倒计时时间大于0 不能发送验证码
  if (timer.value > 0) return

  await formRef.value?.validate('mobile')
  const res = await sendMobileCode(mobile.value, 'login')
  showToast(res.data.code)

  timer.value = 60
  clearInterval(timeId)
  timeId = window.setInterval(() => {
    timer.value--
    if (timer.value <= 0) window.clearInterval(timeId)
  }, 1000)
}

// 挂载的时候清楚定时器
onMounted(() => {
  window.clearInterval(timeId)
})
</script>

<template>
  <div class="login-page">
    <cp-nav-bar
      right-text="注册"
      @click-right="$router.push('/register')"
    ></cp-nav-bar>
    <!-- 头部 -->
    <div class="login-head" @click="isPass = !isPass">
      <h3>{{ isPass ? '密码登录' : '短信验证码登录' }}</h3>
      <a href="javascript:;">
        <span>{{ isPass ? '短信验证码登录' : '密码登录' }}</span>
        <van-icon name="arrow"></van-icon>
      </a>
    </div>
    <!-- 表单 -->
    <van-form autocomplete="off" @submit="login">
      <van-field
        v-model="mobile"
        placeholder="请输入手机号"
        name="mobile"
        :rules="mobileRules"
        type="tel"
      ></van-field>
      <van-field
        v-if="isPass"
        v-model="password"
        :rules="passwordRules"
        placeholder="请输入密码"
        :type="`${isShow ? 'text' : 'password'}`"
      >
        <template #button>
          <cp-icon
            @click="isShow = !isShow"
            :name="`${isShow ? 'login-eye-on' : 'login-eye-off'}`"
          />
        </template>
      </van-field>

      <van-field
        v-else
        v-model="code"
        placeholder="短信验证码"
        :rules="codeRules"
        maxlength="6"
      >
        <template #button>
          <span
            class="btn-send"
            :class="{ active: timer > 0 }"
            @click="sentCode"
            >{{ timer > 0 ? `${timer}s后发送验证码` : '发送验证码' }}</span
          >
        </template>
      </van-field>

      <div class="cp-cell">
        <van-checkbox v-model="agree">
          <span>我已同意</span>
          <a href="javascript:;">用户协议</a>
          <span>及</span>
          <a href="javascript:;">隐私条款</a>
        </van-checkbox>
      </div>
      <div class="cp-cell">
        <van-button block round type="primary" native-type="submit"
          >登 录</van-button
        >
      </div>
      <div class="cp-cell">
        <a href="javascript:;">忘记密码？</a>
      </div>
    </van-form>
    <!-- 底部 -->
    <div class="login-other">
      <van-divider>第三方登录</van-divider>
      <div class="icon">
        <img src="@/assets/qq.svg" alt="" />
      </div>
    </div>
  </div>

  <!-- 封装精灵图 -->
  <!-- <svg aria-hidden="true">
    <use href="#icon-login-eye-off" />
  </svg>
  <cp-icon name="login-eye-off"></cp-icon> -->
</template>

<style lang="scss" scoped>
.login {
  &-page {
    padding-top: 46px;
  }
  &-head {
    display: flex;
    padding: 30px 30px 50px;
    justify-content: space-between;
    align-items: flex-end;
    line-height: 1;
    h3 {
      font-weight: normal;
      font-size: 24px;
    }
    a {
      font-size: 15px;
    }
  }
  &-other {
    margin-top: 60px;
    padding: 0 30px;
    .icon {
      display: flex;
      justify-content: center;
      img {
        width: 36px;
        height: 36px;
        padding: 4px;
      }
    }
  }
}
.van-form {
  padding: 0 14px;
  .cp-cell {
    height: 52px;
    line-height: 24px;
    padding: 14px 16px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    .van-checkbox {
      a {
        color: var(--cp-primary);
        padding: 0 5px;
      }
    }
  }
  .btn-send {
    color: var(--cp-primary);
    &.active {
      color: rgba(22, 194, 163, 0.5);
    }
  }
}
</style>
